<template>
  <div>
    <PhoneForm v-model="newPhoneForm" key="stpe2" ref="newPhoneForm" @handleEnter="submit"/>
    <div class="bind-phone-btn">
      <el-button class="submit-btn"
        :loading="loading"
        type="primary"
        @click="submit">确定</el-button>
    </div>
  </div>
</template>

<script lang='ts'>
import PhoneForm from '@/components/bind-phone-form/index.vue'
import { checkSms } from '@/api/login'
import { kefuUrl } from '@/utils/costum'
// @ts-ignore
import mixins from './bind-mixins'
import { mapState } from 'pinia'
import { userAppStore } from '@/stores/user'
import { invokeAPi } from '@/xz-fn'

export default {
  name: 'ChangeBindPhone',
  components: {
    PhoneForm
  },
  mixins: [mixins],
  props: {
    visible: Boolean
  },
  data () {
    return {
      oldPhoneForm: {
        phoneNumber: '',
        code: '',
        codeID: ''
      },
      newPhoneForm: {
        auth_type: 'phone',
        phoneNumber: '',
        code: '',
        codeID: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapState(userAppStore, ['userInfo'])
  },
  watch: {
    visible: {
      handler (val) {
        if (val) {
          const phoneNumber = this.userInfo.PhoneNumber
          if (phoneNumber) {
            this.oldPhoneForm.phoneNumber = phoneNumber
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    openUrl () {
      this.$xz('xz_open_url', kefuUrl)
    },
    /**
     * 绑定
     */
    submit () {
      this.$refs.newPhoneForm.validate().then((newPhoneForm: any) => {
        const params: any = {
          auth_type: 'phone', // phone-绑定手机,wx-绑定微信
          phone: newPhoneForm.phoneNumber, // 手机号码,auth_type=phone为必填
          auth_code: newPhoneForm.code, // 授权码或者手机验证码
          code_id: newPhoneForm.codeID// 手机验证码对应id,只有授权类型为phone需要
        }
        this.$refs.newPhoneForm.codeError = ''
        this.onBindAuth(params, 'phone').then(() => {
          invokeAPi('xz_substat_action', 1740)
        }).catch((err: any) => {
          if (err && err.code === 12001) {
            this.$refs.newPhoneForm.codeError = '验证码错误'
          }
        })
      })
    },
    resetFields () {
      this.$refs.newPhoneForm && this.$refs.newPhoneForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.bind-phone-btn {
  width: fit-content;
  margin: 58px auto 20px;
}

.submit-btn {
  width: 198px;
}
.tips-wrap {
  margin-top: 12px;
  text-align: right;
}
.contact-btn {
  height: 16px;
  line-height: 16px;
  color: #999999;
  font-size: 12px;
  user-select: none;
  span {
    cursor: pointer;
    &:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>
